package cmc

import (
	"context"
	"fmt"
	model "service/model/crm_base"

	gpc "gitee.com/cloudapex/protos/comm/pb"
	gpb "gitee.com/cloudapex/protos/crm_base/pb"
	gpa "gitee.com/cloudapex/protos/hr_cache/pb"
	"gitee.com/cloudapex/ulern/util"

	hr_cache "service/model/hr_cache"

	mCache "service/model/hr_cache"
	"service/model/mod"

	"strconv"
	"strings"

	"time"

	gpp "gitee.com/cloudapex/protos/crm_base/pb"

	"gitee.com/cloudapex/ulern/htp"
	"github.com/gin-gonic/gin"
)

/**
 *说明：获取首咨库存工作池列表
 * 路由: cmc/work_pool
 * 方法: POST
 */

type GetWorkPoolList struct {
	Page      int64  `form:"page" json:"page" binding:"required"`         //页码
	Pnum      int64  `form:"pnum" json:"pnum" binding:"required"`         //页条数
	StartId   int64  `form:"startId" json:"start_id" binding:"omitempty"` //起始ID
	Order     int64  `form:"order" json:"order" binding:"omitempty"`      //排序字段名：1.入库时间
	Orule     int64  `form:"orule" json:"orule" binding:"omitempty"`      //排序字段名 数据端（1.降序 2.升序）
	UId       int64  `form:"uid" json:"uid" binding:"omitempty"`          //用户ID
	CID       int64  `form:"cid" json:"cid" binding:"omitempty" `         //公司ID
	Phone     int64  `form:"phone" json:"phone" binding:"omitempty"`      //手机号
	CsId      uint64 `form:"csid" json:"csid" binding:"omitempty"`        //客户ID
	Logic     int64  `form:"logic" json:"logic" binding:"omitempty" `     //逻辑库-1 首资，2 公海，3 静默库，4 效率库，5 成交库，6 垃圾库
	Logics    string `form:"logics" json:"logics" binding:"omitempty" `
	Type      int64  `form:"typ" json:"typ" binding:"omitempty" `              //0 默认 1 获取预约列表
	PId       int64  `form:"pid" json:"pid" binding:"omitempty" `              //项目id
	Levels    int64  `form:"levels" json:"levels" binding:"omitempty"`         //意向度 S A B C D
	TestAddre string `form:"testAddre" json:"test_addre" binding:"omitempty" ` //报考地域
	InBgn     int64  `form:"inBgn" json:"inBgn" binding:"omitempty"`           //入库时间(int)
	InEnd     int64  `form:"inEnd" json:"inEnd" binding:"omitempty"`           //入库时间(int)
	BackBgn   int64  `form:"backBgn" json:"backBgn" binding:"omitempty"`       //领取时间(int)
	BackEnd   int64  `form:"backEnd" json:"backEnd" binding:"omitempty"`       //领取时间(int)
	SubmitAt  int64  `form:"submitAt" json:"submitAt" binding:"omitempty"`     //预约时间（int）
	cTimes    []*gpc.TimeReq
}

type WorkPoolRes struct {
	Id        uint64 `json:"id"`        //-- base_project id(14位)
	CId       int64  `json:"cId"`       //-- 公司id
	BId       int64  `json:"bId"`       //-- base_base id
	PPID      int64  `json:"ppid"`      //-- 老项目ID
	PId       int64  `json:"pId"`       //-- 项目id
	PName     string `json:"pName"`     //-- 项目名称
	UId       int64  `json:"uId"`       //-- 用户ID
	UName     string `json:"uName"`     //-- 用户名
	Phone     int64  `json:"phone"`     //-- 手机号（ 可以有默认值，为支持网销团队 ）
	ShowId    uint64 `json:"showId"`    //-- 可见范围ID（员工自己的showId）
	Levels    int64  `json:"levels"`    //-- 意向度 S A B C D
	Info      string `json:"info"`      //-- 机会详情
	CallAt    int64  `json:"callAt"`    //-- 最近拨打时间
	CallCount int64  `json:"callCount"` //-- 拨打次数
	Logic     int64  `json:"logic"`     //-- 逻辑库-1 首资，2 公海，3 静默库，4 效率库，5 成交库，6 垃圾库
	FirstAt   int64  `json:"firstAt"`   //-- 首次拨打时间
	At        int64  `json:"at"`        //-- 获取时间
	NoteAt    int64  `json:"noteAt"`    //-- 最近备注时间
	TestAddre string `json:"testAddre"` //-- 报考地址（员工自己填写，留编辑入库）
	Submit    int64  `json:"submit"`    //-- 预约时间
}

type ProjectListRes struct {
	ID    int64  `json:"id"`     //ID
	PId   int64  `json:"p_id"`   //项目ID
	PName string `json:"p_name"` //项目名称
}

func (this *GetWorkPoolList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	var work_pol gpb.WorkPool
	jwtUser := mod.CurrUser(c)
	if resp := this.HandleCondiTimes(c, ctx); resp.Err() != nil {
		return resp
	}

	var list []int64
	if this.Logics != "" {
		logicList := strings.Split(this.Logics, ",")
		for _, v := range logicList {
			v1, _ := strconv.ParseInt(v, 10, 64)
			list = append(list, v1)
		}
	}

	work_pol.UId = jwtUser.UId
	work_pol.CId = jwtUser.CId
	work_pol.Phone = this.Phone
	work_pol.Id = this.CsId
	work_pol.Logic = this.Logic
	work_pol.Logics = list
	work_pol.PId = this.PId
	work_pol.Levels = this.Levels
	work_pol.TestAddre = this.TestAddre
	work_pol.TimeReq = this.cTimes
	fmt.Println("cid : ", work_pol.CId, "uid ", work_pol.UId)
	sysreq := gpb.WorkPoolReq{WorkPool: &work_pol, StartId: this.StartId, Page: this.Page, Count: this.Pnum, DesClum: 1, IsDes: this.Orule, Type: this.Type}
	rsp, err := model.Work.GetWorkPoolList(ctx, &sysreq)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	pidlist := gpp.ProjectListReq{Project: &gpb.Project{CId: jwtUser.CId}, Page: 1, Count: 100, DesClum: 1, IsDes: 2}
	projct, err := model.Proj.GetProjectList(ctx, &pidlist)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	val := make([]ProjectListRes, 0)
	for _, v := range projct.Project {
		val = append(val, ProjectListRes{v.Id, v.ProId, v.Name})
	}
	userlist := make([]WorkPoolRes, 0)
	for _, s := range rsp.WorkPool {
		var info WorkPoolRes
		util.Convert(&info, s)
		for _, i := range val {
			if i.ID == s.PId {
				info.PPID = i.PId
				info.PName = i.PName
				break
			}
		}
		userlist = append(userlist, info)
	}
	return htp.RespOK("", &struct {
		Total int         `json:"total"`
		List  interface{} `json:"list"`
	}{int(rsp.Count), userlist})
}

func (this *GetWorkPoolList) HandleCondiTimes(c *gin.Context, ctx context.Context) htp.Response {
	if this.InBgn != 0 { // 入库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 1, Start: this.InBgn, End: this.InEnd})
	}
	if this.BackBgn != 0 { // 回库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 3, Start: this.InBgn, End: this.InEnd})
	}
	if this.SubmitAt != 0 { // 回库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 4, Start: this.InBgn, End: this.InEnd})
	}
	return htp.RespOK("", nil)
}

/*
 *说明：机会查询
 *路由: cmc/csid_info
 *方法: GET
 */

type GetCsIdInfo struct {
	Order int64  `form:"order" json:"order" binding:"omitempty"` //排序字段名：1.入库时间
	Orule int    `form:"orule" json:"orule" binding:"omitempty"` //排序字段名 数据端（1.降序 2.升序）
	UId   int64  `form:"uid" json:"uid" binding:"omitempty"`     //用户ID
	CID   int64  `form:"cid" json:"cid" binding:"omitempty" `    //公司ID
	Phone int64  `form:"phone" json:"phone" binding:"omitempty"` //手机号
	CsId  uint64 `form:"csid" json:"csid" binding:"omitempty"`   //客户id
	PId   int64  `form:"pId" json:"pId" binding:"omitempty"`     //项目ID
}
type getCsIdRspItem struct {
	Base model.BaseBase     `json:"baseBase"`
	Proj model.BaseProjects `json:"baseProject"`
}

func (this *GetCsIdInfo) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)
	if this.Phone == 0 && this.CsId == 0 {
		return htp.RespModelErr("客户ID和手机号必须选其一", nil)
	}
	rsp, err := model.Base.GetPoolList(ctx, &gpb.BasePoolReq{Page: 1, Count: 10, BasePool: &gpb.BasePool{
		BaseBase: &gpb.BaseBase{
			Phone: this.Phone,
		},
		BaseProject: &gpb.BaseProject{
			CId: user.CId,
			Id:  this.CsId,
			PId: this.PId,
		},
	}})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if rsp.Message == "暂无数据" {
		return htp.RespOK("暂无数据", nil)
	}
	items := []*getCsIdRspItem{}
	ids := []int64{}
	for _, ss := range rsp.BasePool {
		ids = append(ids, ss.BaseProject.UId)
	}
	if err := util.Convert(&items, rsp.BasePool); err != nil {
		return htp.RespConvertErr("", err)
	}
	userListRes, errl := hr_cache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: ids})
	fmt.Println("userListRes.NameList   : ", userListRes.NameList)
	if errl != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		for _, kv := range userListRes.NameList {
			if it.Proj.UId == kv.Id {
				it.Proj.RoleId = kv.Role
			}
		}
	}
	// 处理项目PPID
	if resp := this.HandleProjNames(c, ctx, items); nil != resp.Err() {
		return resp
	}

	// 处理组织架构名称
	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	//处理坐席名称
	if resp := this.HandleUserNames(c, ctx, items); nil != resp.Err() {
		return resp
	}

	return htp.RespOK("", &struct {
		Total int         `json:"total"`
		List  interface{} `json:"list"`
	}{int(rsp.Count), items})
}

func (this *GetCsIdInfo) HandleProjNames(c *gin.Context, ctx context.Context, items []*getCsIdRspItem) htp.Response {
	rsp, err := model.Proj.GetProjectList(ctx, &gpp.ProjectListReq{
		Page: 1, Count: 100, DesClum: 1, IsDes: 2,
		Project: &gpb.Project{},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range rsp.Project {
		for _, item := range items {
			if item.Proj.PId == it.Id {
				item.Proj.PPId = it.ProId
				item.Proj.ProjName = it.Name
				break
			}
		}
	}
	return htp.RespOK("", nil)
}

func (this *GetCsIdInfo) HandleFrameNames(c *gin.Context, ctx context.Context, items []*getCsIdRspItem) htp.Response {
	user := mod.CurrUser(c)

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Proj.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}
	for _, it := range items {
		it.Proj.ShowName = mapShowNames[it.Proj.ShowId]
	}
	return htp.RespOK("", nil)
}

func (this *GetCsIdInfo) HandleUserNames(c *gin.Context, ctx context.Context, items []*getCsIdRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Proj.UId, it.Proj.FirstId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Proj.UName = mapNames[it.Proj.UId]
		it.Proj.FirstName = mapNames[it.Proj.FirstId]
	}
	return htp.RespOK("", nil)
}

/*
	说明 :修改机会基本信息
*/

type EditPoolRes struct {
	Id          uint64 `json:"id" form:"id" binding:"omitempty"`                   //机会ID baseBase  id
	Name        string `json:"name" form:"name" binding:"omitempty"`               //学员姓名
	Address     string `json:"address" form:"address" binding:"omitempty"`         //地域
	Sex         int64  `json:"sex" form:"sex" binding:"omitempty"`                 //性别 0 默认 1 男 2 女  性别
	Srank       int64  `json:"srank" form:"srank" binding:"omitempty"`             //学历 1 初中以下, 2 中专 3 高中 4 大专 5 本科， 6 硕士， 7 博士
	Major       string `json:"major" form:"major" binding:"omitempty"`             //专业
	Phone       int64  `json:"phone" form:"phone" binding:"omitempty"`             //手机号（ 可以有默认值，为支持网销团队 ）
	DeputyNo    int64  `json:"deputyNo" form:"deputyNo" binding:"omitempty"`       //副号
	WeChar      string `json:"weChar" form:"weChar" binding:"omitempty"`           //微信号
	State       int64  `json:"state" form:"state" binding:"omitempty"`             //本库状态： 1 - 100 ： 可以拨打状态 100 - 200 不可拨打状态( 100 空号， 101 静默号 )
	Qq          int64  `json:"qq" form:"qq" binding:"omitempty"`                   //QQ号
	CsId        uint64 `json:"cs_id" form:"cs_id" binding:"omitempty"`             //机会的项目ID proid+bid(14位)
	CId         int64  `json:"cId" form:"cId" binding:"omitempty"`                 //公司id
	BId         uint64 `json:"bId" form:"bId" binding:"omitempty"`                 //base_base id
	PId         int64  `json:"pId" form:"pId" binding:"omitempty"`                 //project id
	UId         int64  `json:"uId" form:"uId" binding:"omitempty"`                 //当前领取坐席ID
	Station     int64  `json:"station" form:"station" binding:"omitempty"`         //站点ID
	StationShow uint64 `json:"stationShow" form:"stationShow" binding:"omitempty"` //站点可见范围（ 可分配数据区间 ）
	ShowId      uint64 `json:"showId" form:"showId" binding:"omitempty"`           //可见范围ID
	FirstId     int64  `json:"firstId" form:"firstId" binding:"omitempty"`         //首次领取坐席
	ToAt        int64  `json:"toAt" form:"toAt" binding:"omitempty"`               //最近一次领取时间
	SId         string `json:"sId" form:"sId" binding:"omitempty"`                 //来源id 渠道  导入数据需追加来源ID
	Info        string `json:"info" form:"info" binding:"omitempty"`               //机会详情
	CallCount   int64  `json:"callCount" form:"callCount" binding:"omitempty"`     //累计拨打次数
	CallLength  int64  `json:"callLength" form:"callLength" binding:"omitempty"`   //累计拨打时长
	Logic       int64  `json:"logic" form:"logic" binding:"omitempty"`             //逻辑库-1 首资，2 公海，3 静默库，4 效率库，5 成交库，6 垃圾库
	BackAt      int64  `json:"backAt" form:"backAt" binding:"omitempty"`           //回公海时间 ( 由效率库回公海的时间 )
	Levels      int64  `json:"levels" form:"levels" binding:"omitempty"`           //意向度  1.A 2.B 3.C 4.D 5.E
	InType      int64  `json:"inType" form:"inType" binding:"omitempty"`           //入库方式 1首资入库，2销售创建，3批量导入
	SAccount    string `json:"sAccount" form:"sAccount" binding:"omitempty"`       //推广账户
	SWay        int64  `json:"sWay" form:"sWay" binding:"omitempty"`               //推广方式（sem,信息流）
}

func (this *EditPoolRes) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtUser := mod.CurrUser(c)
	rsp, err := model.Base.EditPool(ctx, &gpb.BasePoolReq{
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{
				Id:       this.Id,
				Phone:    this.Phone,
				DeputyNo: this.DeputyNo,
				Name:     this.Name,
				WeChar:   this.WeChar,
				Address:  this.Address,
				Sex:      this.Sex,
				Srank:    this.Srank,
				Major:    this.Major,
			},
			BaseProTg: &gpb.BaseProTg{},
			BaseProject: &gpb.BaseProject{
				Id:     this.CsId,
				Levels: this.Levels,
			},
		},
	})
	fmt.Println("-----------------------------------------------------------   : ")
	fmt.Println("rsp   : ", rsp, "      ---------          err  :::::", err)
	fmt.Println("-----------------------------------------------------------   : ")
	if nil != err {
		return htp.RespModelErr("", err)
	}
	if _, err := model.Work.EditWorkPool(ctx, &gpb.WorkPool{
		UId:       jwtUser.UId,
		Id:        this.CsId,
		Levels:    this.Levels,
		TestAddre: this.Address,
	}); nil != err {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("修改成功", nil)
}

/**
 *说明：索取首咨（领取成功后server调用对应方法插入工作池）
 *参数：p_id   项目ID
 *     uId		当前领取坐席ID
 *     showId 当前坐席showId ,多个取最小一级
 *     stationShow  此人绑定的领取站点ID 根据hid从缓存中获取
 *  GET
 *	rpc GetFirstConsu(FirstConsuReq) returns (PoolRes) {}
 */

type GetFirstConsuRes struct {
	PId         int64    `json:"pId" form:"pId" binding:"omitempty"`                 //项目ID
	Uid         int64    `json:"uid" form:"uid" binding:"omitempty"`                 //当前领取坐席ID
	ShowId      uint64   `json:"showId" form:"showId" binding:"omitempty"`           //当前坐席showId ,多个取最小一级
	StationShow []uint64 `json:"stationShow" form:"stationShow" binding:"omitempty"` //此人绑定的领取站点ID 根据hid从缓存中获取
}

func (this *GetFirstConsuRes) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtuser := mod.CurrUser(c)
	fmt.Println(jwtuser.CId, "-----", jwtuser.ShowId[0])
	if 0 == this.PId {
		return htp.RespModelErr("项目id不可为空 ", nil)
	}
	//获取一条首资数据
	list, err := model.Base.GetFirstConsu(ctx, &gpb.FirstConsuReq{
		PId:         this.PId,
		UId:         jwtuser.UId,
		ShowId:      jwtuser.ShowId[0],
		StationShow: jwtuser.ShowId,
	})
	if nil != err {
		return htp.RespModelErr("", err)
	}
	// （首资）
	// 添加工作池
	if _, err = model.Work.WorkPoolAdd(ctx, &gpb.WorkPool{
		Id:     list.BasePool.BaseProject.Id,
		CId:    jwtuser.CId,
		BId:    list.BasePool.BaseBase.Id,
		PId:    list.BasePool.BaseProject.PId,
		UId:    jwtuser.UId,
		UName:  jwtuser.Name,
		Phone:  list.BasePool.BaseBase.Phone,
		ShowId: mod.SectionMaxLv(jwtuser.ShowId),
		Levels: list.BasePool.BaseProject.Levels,
		Info:   list.BasePool.BaseProject.Info,
		Logic:  list.BasePool.BaseProject.Logic,
		At:     time.Now().Unix(),
	}); err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("领取成功1条", nil)
}

//}
/**---------------------一个项目一个队列-------------------------------------
 *说明：签到接口，签到后参数自动分首咨
 *参数：uId	当前领取坐席ID
 *     p_id[] 多个项目ID（重新设置之后调用更新）
 *     grade  当前坐席分配等级 A.5 B.4 C.3 D.2 E.1 F.0
 *     showId 当前坐席showId ,多个取最小一级（重新设置之后调用更新）
 *     stationShow[]  此人绑定的领取站点ID 根据hid从缓存中获取（重新设置之后调用更新）
 *     WorkPoolCount  首咨池总数量上限 200（重新设置之后调用更新）
 */

type SignFirstConsuRes struct {
	PId         []int64  `json:"p_id" form:"p_id" binding:"omitempty"`              //项目ID
	Uid         int64    `json:"uid" form:"uid" binding:"omitempty"`                //当前领取坐席ID
	ShowId      uint64   ` json:"showId" form:"showId" json:"showId"`               //当前坐席showId ,多个取最小一级
	StationShow []uint64 `json:"stationShow" form:"stationShow" json:"stationShow"` //此人绑定的领取站点ID 根据hid从缓存中获取
}

func (this *SignFirstConsuRes) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtuser := mod.CurrUser(c)
	if _, err := model.Base.SignFirstConsu(ctx, &gpb.SignFirstConsuReq{
		PId:         this.PId,
		UId:         jwtuser.UId,
		ShowId:      mod.SectionMaxLv(jwtuser.ShowId),
		StationShow: this.StationShow,
	}); nil != err {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("签到成功", nil)
}

/**
 * @explain : 索取首资 已领/上限
 * @Request method : GET
 * @address :
 * @remarks :
 **/

/**
 * @explain : 项目 领取时间间隔
 * @Request method : GET
 * @address :
 * @remarks :
 **/

//---------------------------------------------------------------------------------

// 数据列表公共入参表
type CommDataInParam struct {
	CsId      int64  `form:"csId" json:"csId" binding:"omitempty"`             // 客户Id
	UserId    int64  `form:"userId" json:"userId" binding:"omitempty"`         // 坐席Id
	Phone     int64  `form:"phone" json:"phone" binding:"omitempty"`           // 手机号
	ProjId    int64  `form:"projId" json:"projId" binding:"omitempty"`         // 项目Id
	Levels    int64  `form:"levels" json:"levels" binding:"omitempty"`         //意向度 S A B C D
	TestAddre string `form:"testAddre" json:"test_addre" binding:"omitempty" ` //报考地域
}

/*
 * 描述: 首咨|库存列表[已分配时]
 * 路由: /data/firstBaseListed
 * 方法: GET
 *********************************************************************/
type FirstBaseListed struct {
	mod.SortFinder // 3:领取时间 4:沟通时间
	mod.PageFinder
	CommDataInParam        // 公共入参
	Logic           int64  `form:"logic" json:"Logic" binding:"omitempty"` // 1:首咨(默认) 2:库存
	Logics          string `form:"logics" json:"Logics" binding:"omitempty"`
	TGChannel       int    `form:"tgChannel" json:"tgChannel" binding:"omitempty"` // 推广渠道
	TGMode          int    `form:"tgMode" json:"tgAssign" binding:"omitempty"`     // 推广方式
	BackBgn         int64  `form:"backBgn" json:"backBgn" binding:"omitempty"`     //领取时间(int)
	SubmitAt        int64  `form:"submitAt" json:"submitAt" binding:"omitempty"`   //预约时间（int）
	Type            int64  `form:"typ" json:"typ" binding:"omitempty" `            //0 默认 1 获取预约列表
	Start           int64  `form:"start" json:"start" binding:"omitempty" `        //开始时间
	End             int64  `form:"end" json:"end" binding:"omitempty" `            //结束时间

	cTimes []*gpc.TimeReq
}

type TimeReq struct {
	Tag   int64 `form:"tag" json:"tag" binding:"omitempty" ` // 1:入库时间 2:回库时间 3:领取时间 4.预约时间 5:登记时间 6分配时间
	Start int64 `form:"start" json:"start" binding:"omitempty" `
	End   int64 `form:"end" json:"end" binding:"omitempty" `
}

type firstBaseListedRspItem struct {
	Work *model.WorkPool  `json:"workPool"`
	Tg   *model.WorkProTg `json:"workProTg"`
}

func (this *FirstBaseListed) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)
	fmt.Println(this.Logics)
	var list []int64
	if this.Logics != "" {
		logicList := strings.Split(this.Logics, ",")
		for _, v := range logicList {
			v1, _ := strconv.ParseInt(v, 10, 64)
			list = append(list, v1)
		}
	}
	if resp := this.HandleCondiTimes(c, ctx); resp.Err() != nil {
		return resp
	}
	rsp, err := model.Work.GetWorkPoolTgList(ctx, &gpb.WorkPoolTgReq{
		Page:    int64(this.PageFinder.Page),
		Count:   int64(this.PageFinder.Pnum),
		DesClum: int64(this.SortFinder.Order),
		IsDes:   int64(this.SortFinder.Orule + 1), // 已分配
		WorkPoolTg: &gpb.WorkPoolTg{
			WorkPool: &gpb.WorkPool{
				Phone:     this.Phone,
				Id:        uint64(this.CsId),
				UId:       user.UId,
				CId:       user.CId,
				PId:       this.ProjId,
				Logic:     this.Logic,
				Logics:    list,
				Levels:    this.Levels,
				TestAddre: this.TestAddre,
				TimeReq:   this.cTimes,
			},
			WorkProTg: &gpb.WorkProTg{
				ChannelId: int64(this.TGChannel),
				WayId:     int64(this.TGMode),
			},
		},
		Type: this.Type,
	})
	fmt.Println(this.TestAddre)
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*firstBaseListedRspItem{}

	projct, err := model.Proj.GetProjectList(ctx, &gpp.ProjectListReq{Project: &gpb.Project{CId: user.CId}, Page: 1, Count: 100, DesClum: 1, IsDes: 2})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	val := make([]ProjectListRes, 0)
	for _, v := range projct.Project {
		val = append(val, ProjectListRes{v.Id, v.ProId, v.Name})
	}
	for _, s := range rsp.WorkPoolTg {
		var info *firstBaseListedRspItem
		util.Convert(&info, s)
		for _, i := range val {
			if i.ID == s.WorkPool.PId {
				info.Work.PPID = i.PId
				info.Work.PName = i.PName
				break
			}
		}
		items = append(items, info)
	}

	if err := util.Convert(&items, rsp.WorkPoolTg); err != nil {
		return htp.RespConvertErr("", err)
	}

	if resp := this.HandleFrameNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	if resp := this.HandleUserNames(c, ctx, items); resp.Err() != nil {
		return resp
	}

	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{rsp.Count, items})
}
func (this *FirstBaseListed) HandleProjNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)

	names, err := model.Proj.GetProjIdNames(ctx, user.CId)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, it := range items {
		it.Work.PName = names[it.Work.PId]
	}
	return htp.RespOK("", nil)
}
func (this *FirstBaseListed) HandleFrameNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uShowIds := []uint64{}
	for _, it := range items {
		uShowIds = append(uShowIds, it.Work.ShowId)
	}
	uShowIds = util.RemoveDuplicateU64(uShowIds)
	rsp, err := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, &gpa.FullReqUIdsReq{CId: user.CId, Ids: uShowIds})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}

	mapShowNames := map[uint64]string{}
	for _, it := range rsp.FullUList {
		mapShowNames[it.Id] = it.FullName
	}

	for _, it := range items {
		it.Work.ShowName = mapShowNames[it.Work.ShowId]
	}
	return htp.RespOK("", nil)
}
func (this *FirstBaseListed) HandleUserNames(c *gin.Context, ctx context.Context, items []*firstBaseListedRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		uIds = append(uIds, it.Work.UId)
	}
	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}
	for _, it := range items {
		it.Work.UName = mapNames[it.Work.UId]
	}
	return htp.RespOK("", nil)
}

func (this *FirstBaseListed) HandleCondiTimes(c *gin.Context, ctx context.Context) htp.Response {
	if this.BackBgn != 0 { // 回库
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 3, Start: this.Start, End: this.End})
	}
	if this.SubmitAt != 0 { // 预约
		this.cTimes = append(this.cTimes, &gpc.TimeReq{Tag: 4, Start: this.Start, End: this.End})
	}
	return htp.RespOK("", nil)
}
